<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
          padding: 0;
          margin: 0;
          border: none;
        }
        .pic {
          vertical-align: top;
        }
        #main {
          position: relative;
          height: 100vh;
          overflow: auto;
        }
        .box {
          float: left;
          padding: 15px 0 0 15px;
        }
        .pic{
          width: 200px;
          cursor: pointer;
        }
        img{
          width: 100%;
          height: 100%;
        }
      </style>
</head>
<body>
    <div id="main"></div>
</body>
<script>
    let mainBox = document.querySelector("#main");

    function getRandomArbitrary(min=100, max=280) {
        return (Math.random() * (max - min) + min)+'px';
    }
    let imgSrc = [
       'https://pic3.zhimg.com/v2-21360f2a178a35880b1cb23b98a4a272_r.jpg',
       'https://pic2.zhimg.com/v2-f9bd2aee5d3b61fef3a4c9460c33a825_r.jpg',
       'https://pic1.zhimg.com/v2-805c7260172ec8465e40553d62aa9e88_r.jpg',
       'https://pic1.zhimg.com/v2-3750d14017353f5f12eb5641a73419f4_r.jpg',
       'https://pic2.zhimg.com/v2-5f720dabc544672416797cdcdcdae109_r.jpg',
       'https://pic3.zhimg.com/v2-c1b00dd2c3d5c214decfcd422ed62342_r.jpg',
       'https://pic4.zhimg.com/80/v2-13686cdc05355db47af988d9989e993b_720w.webp',
       'https://pic4.zhimg.com/v2-cb1e5b12cdc816f9acfacce79d453807_r.jpg',
       'https://pic.rmb.bdstatic.com/bjh/news/af49f9d6a3a674321316ded5986987b5.jpeg',
       'https://img1.pconline.com.cn/piclib/200803/12/batch/1/111/1205333297849x89le15uul.jpg'
    ]
    function getRandomElement(arr) {
        return arr[Math.floor(Math.random() * arr.length)];
    }
    for (let index = 0; index < 50; index++) {
        let box = document.createElement('div');
        box.className = 'box';
        let pic = document.createElement('div');
        pic.className = 'pic';
        pic.style.height = getRandomArbitrary();
        let img = document.createElement('img');
        img.src = getRandomElement(imgSrc);
        pic.appendChild(img);
        box.appendChild(pic);
        mainBox.appendChild(box);
        waterFall('main','box');
    }
    window.addEventListener("load",function() {
        let pic = document.querySelectorAll('.pic');
        for (let i = 0; i < pic.length; i++) {
          pic[i].addEventListener('click',(e)=>{
            window.open(e.target.src)
          })
        }
    })

    mainBox.addEventListener('scroll', function(){
        // 当滚动到底部时，元素的滚动高度会等于其总高度减去其可视区域的高度
        if (this.scrollHeight - this.scrollTop === this.clientHeight) {
            for (let index = 0; index < 9; index++) {
                let box = document.createElement('div');
                box.className = 'box';
                let pic = document.createElement('div');
                pic.className = 'pic';
                pic.style.height = getRandomArbitrary();
                let img = document.createElement('img');
                img.src = getRandomElement(imgSrc);
                pic.appendChild(img);
                box.appendChild(pic);
                mainBox.appendChild(box);
                waterFall('main','box');
                let pics = document.querySelectorAll('.pic');
                for (let i = 0; i < pics.length; i++) {
                  pics[i].addEventListener('click',(e)=>{
                    window.open(e.target.src)
                  })
                }
            }
        }
    })
    


/*
  实现瀑布流布局，传递参数为string类型
*/
function waterFall(parent,child) {
  //1、根据图片的列数来确定父盒子的宽度，父盒子居中
  //1.1 获取标签，父盒子和所有子盒子
  var father= document.getElementById(parent);
  var allBox = document.getElementsByClassName(child); 
  //1.2 获取其中一个的宽度
  var boxWidth = allBox[0].offsetWidth;
  //1.3 获取文档的宽度(兼容)
  var screen = document.documentElement.clientWidth || document.body.clientWidth;
  //1.4 求出当前图片的列数，是变化的
  var cols = parseInt(screen / boxWidth);
  //1.5 父盒子居中，给父盒子设置宽度
  father.style.width = (cols * boxWidth + 20) + 'px';
  father.style.margin = '0 auto';

  //2、子盒子定位（从第二行开始）
  //2.1 定义变量
   var heightArr = [], boxHeight = 0, minBoxHeight = 0, minIndex = 0;
  //2.2 遍历所有的盒子
  for(let i = 0;i < allBox.length; i++) {
    boxHeight = allBox[i].offsetHeight;
    //2.3 判断是否是第一行
    if(i < cols) {
      heightArr.push(boxHeight)
    }else { //剩余行做定位
      //2.4 取出数组中最矮盒子的高度
      minBoxHeight = heightArr[minBox(heightArr)];
      //2.5 取出最矮盒子再数组中的索引
      minIndex = minBox(heightArr);
      //2.6 剩余子盒子的定位
      allBox[i].style.position = 'absolute';
      allBox[i].style.left = minIndex * boxWidth + 'px';
      allBox[i].style.top = minBoxHeight + 'px';
      //2.7 更新高度
      heightArr[minIndex] += boxHeight;
    }
  }
  
}

function minBox(box) {
  var j = 0;
  for(i in box) {
    if(box[j] > box[i])
      j = i
  }
  return j;
}
</script>
</html>